<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 添加账本ID到分类表
        Schema::table('money_categories', function (Blueprint $table) {
            $table->unsignedBigInteger('book_id')->after('id')->comment('账本ID');
            $table->foreign('book_id')->references('id')->on('money_books')->onDelete('cascade');
        });
        
        // 添加账本ID到子分类表
        Schema::table('money_sub_categories', function (Blueprint $table) {
            $table->unsignedBigInteger('book_id')->after('id')->comment('账本ID');
            $table->foreign('book_id')->references('id')->on('money_books')->onDelete('cascade');
        });
        
        // 添加账本ID到交易记录表
        Schema::table('money_transactions', function (Blueprint $table) {
            $table->unsignedBigInteger('book_id')->after('id')->comment('账本ID');
            $table->foreign('book_id')->references('id')->on('money_books')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // 移除交易记录表中的账本ID
        Schema::table('money_transactions', function (Blueprint $table) {
            $table->dropForeign(['book_id']);
            $table->dropColumn('book_id');
        });
        
        // 移除子分类表中的账本ID
        Schema::table('money_sub_categories', function (Blueprint $table) {
            $table->dropForeign(['book_id']);
            $table->dropColumn('book_id');
        });
        
        // 移除分类表中的账本ID
        Schema::table('money_categories', function (Blueprint $table) {
            $table->dropForeign(['book_id']);
            $table->dropColumn('book_id');
        });
    }
};